package com.oly.cms.hand.security.hand;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.alibaba.fastjson2.JSONObject;
import com.grace.common.core.domain.AjaxResult;

/** 认证异常处理类 */
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        if (isAjaxRequest(request)) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(AjaxResult.error(authException.getMessage())));
            response.getWriter().flush();
            response.getWriter().close();
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, authException.getMessage());
        }

    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }
}